package com.sg.record.aop;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.ModelAndView;

import com.sg.common.empty.aop.CustomerAop;
import com.sg.common.empty.core.Params2;
import com.sg.common.empty.entity.Cons;
import com.sg.common.empty.service.CfgService;
import com.sg.common.login.entity.Member;
import com.sg.common.login.entity.Org;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
import com.sg.common.utils.ReUtils;

public class CompLogAdd  extends CustomerAop {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	CfgService service;
	
	@Override
	// 1
	public String pre(HttpServletRequest request, HttpServletResponse response,
			Object handler) {
		// TODO Auto-generated method stub
		String rt = "";
		
      String route = (String) request.getAttribute("conf.route");
		
		
		//综合日志的添加
//		String oransql = Constant.get(route + ".sql");
//		List<String> sqlParams = Params2.init(request,requestBody,service).build();
//		service.excuteBySql(oransql, sqlParams.toArray());
		if (StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
			Object bean = request.getAttribute("bean");
			Member m = (Member) request.getSession().getAttribute(
					"SESSION_MEMBER");
			//原根据创建时间判断日期规则（当日中午12时前为前天日志，12时后为当天日期）修改为当天日期-----2017.10.16
			/*Date date = DateTimeUtils.strToDate(DateTimeUtils.getCurrentDate()
					+ " " + "12:00:00", "yyyy-MM-dd HH:mm:ss");
			int i = new Time(System.currentTimeMillis()).compareTo(date);*/

			try {
				ReUtils.set(bean, "onDuty", m.getDescr());
				//原根据创建时间判断日期规则（当日中午12时前为前天日志，12时后为当天日期）修改为当天日期-----2017.10.16
				/*if (i > 0) {
					ReUtils.set(bean, "date", DateTimeUtils.getCurrentDate());
				} else {
					ReUtils.set(bean, "date", DateTimeUtils.findYesterday());
				}*/
				ReUtils.set(bean, "date", DateTimeUtils.getCurrentDate());
//				ReUtils.set(bean, "enable", "1");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error(e.getMessage());
			}

			// getService().update(bean);
		}

		if (StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {
			Object bean = request.getAttribute("bean");
			if(bean!=null){
				try {
					String date = ReUtils.getStr(bean, "date");
					Object org = ReUtils.get(bean, "org");
					if(org!=null){
						String shift = ReUtils.getStr(bean, "shift");

						if(shiftCheck(shift)){
							
								DetachedCriteria 
								dc = DetachedCriteria.forClass(Org.class);
								dc.add(Restrictions.eq("id", ReUtils.getStr(org, "id")));
								org = getService().findBean(dc);
								if (!StringUtils.equalsIgnoreCase(
										ReUtils.getStr(org, "orglv"), "3")) {
									rt = "请选择正确的车站（组织）！";
								} else {
									// DetachedCriteria
									// 同一日期，同一车站，同一班次，仅能有一个日志
//									dc = DetachedCriteria.forClass(CompLog.class);
									/*dc.add(Restrictions.eq("date", date))
											.add(Restrictions.eq("org", org))
											.add(Restrictions.eq("shift", shift))
											.add(Restrictions.in("enable", new String[] {
													"1", "2" }));
									Object compLog = getService().findBean(dc);
									if (compLog != null) {
										rt = "无法新增日志，日期、班次信息请核实！";
									}*/
									//2017-9-7 更新 ---新增时,该组织下的所有日志必须为发布(已交接班确认)状态
//									dc.add(Restrictions.eq("org",org)).add(Restrictions.eq("enable", "1"));
//									List<CompLog> compList = getService().find(dc);
//									if(!compList.isEmpty()){
//										rt = "无法新增日志,请确认本车站/工班,所有日志已交接班完成!";
//									}
								}
						}else{
							rt = "班次信息请核对！";
						}
					}else{
						logger.error("No bean specified定位???pre--org为空，请核实组织信息后再提交!");
						rt = "请核实组织信息后再提交!";
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error(e.getMessage());
				}
			}else{
				logger.error("No bean specified定位???pre--bean为空，请核实页面信息（日期、组织、班次）无误后再提交！");
				rt = "请核实页面信息（日期、组织、班次）无误后再提交！";
			}
			
		}
		return rt;
	}

	private Boolean shiftCheck(String shift) {
		Boolean canDo = false;
		DetachedCriteria dc = DetachedCriteria.forClass(Cons.class);
		dc.createAlias("domain", "d");
		dc.add(Restrictions.eq("d.domain","stbook_record_shift"));
		List<Cons> cons = getService().find(dc);
		for(Cons c:cons){
			if(StringUtils.equalsIgnoreCase(c.getValue(), shift)){
				canDo = true;
				break;
			}
		}
		
		return canDo;
	}

//	@Override
//	// 3
//	public void after(HttpServletRequest request, HttpServletResponse response,
//			Object handler) {
//		// TODO Auto-generated method stub
//		if (StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {
//			Object bean = request.getAttribute("bean");
//			if(bean!=null){
//				try {
//					Object compLog = findLastComp(bean);
//
//					// 当班期间重要事项 1、2~待处理、待交接
//					DetachedCriteria dc = DetachedCriteria.forClass(Impth.class);
//					dc.add(Restrictions.eq("compLog", compLog)).add(
//							Restrictions.in("enable", new String[] { "1", "2" }));
//					List<Impth> imL = getService().find(dc);
//					for (Impth i : imL) {
//						// 需处理事项，直接copy；待交接事项，根据pasts值判断是否需要copy过来显示0
//						if (StringUtils.equalsIgnoreCase(i.getEnable(), "1")
//								|| (StringUtils
//										.equalsIgnoreCase(i.getEnable(), "2") && needCreate(i
//										.getPasts()))) {
//							Object impth = createImpth(request, bean, i);
//							getService().save(impth);
//						}
//					}
//
//					// 客伤、客诉 1、2、~待处理、待交接
//					dc = DetachedCriteria.forClass(Complain.class);
//					dc.add(Restrictions.eq("compLog", compLog)).add(
//							Restrictions.in("enable", new String[] { "1", "2" }));
//					List<Complain> cpL = getService().find(dc);
//					for (Complain c : cpL) {
//						if (StringUtils.equalsIgnoreCase(c.getEnable(), "1")
//								|| ((StringUtils.equalsIgnoreCase(c.getEnable(),
//										"2")) && needCreate(c.getPasts()))) {
//							Object complain = createComplain(request, bean, c);
//							getService().save(complain);
//						}
//					}
//
//					dc = DetachedCriteria.forClass(Injured.class);
//					dc.add(Restrictions.eq("compLog", compLog)).add(
//							Restrictions.in("enable", new String[] { "1", "2" }));
//					List<Injured> inL = getService().find(dc);
//					for (Injured i : inL) {
//						if (StringUtils.equalsIgnoreCase(i.getEnable(), "1")
//								|| ((StringUtils.equalsIgnoreCase(i.getEnable(),
//										"2")) && needCreate(i.getPasts()))) {
//							Object injured = createInjured(request, bean, i);
//							getService().save(injured);
//						}
//					}
//					//交接内容
//					dc = DetachedCriteria.forClass(HandOver.class);
//					dc.add(Restrictions.eq("compLog", compLog)).add(Restrictions.eq("yorn", "1"));
//					List<HandOver> handOverList = getService().find(dc);
//					for(HandOver ho:handOverList){
//						Object handOver = createHandOver(request, bean, ho);
//						getService().save(handOver);
//					}
//					
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					logger.error(e.getMessage());
//				}
//			}else{
//				logger.error("No bean specified定位???after--bean为空，日志相关待交接事项、客伤、客诉、交班内容未创建！");
//			}
//			
//		}
//
//	}
//
//	private Object createHandOver(HttpServletRequest request, Object bean,
//			HandOver ho) throws IllegalAccessException,
//			InvocationTargetException, NoSuchMethodException {
//		HandOver handOver = new HandOver();
//		ReUtils.set(handOver, "compLog", bean);
//		ReUtils.set(handOver, "content", ho.getContent());
//		ReUtils.set(handOver, "remark", ho.getRemark());
//		ReUtils.set(handOver, "enable", ho.getEnable());
//		ReUtils.set(handOver,"yorn",ho.getYorn());
//		ReUtils.set(handOver, "parent", ho);
//		ReUtils.set(handOver,"createMember",request.getSession()
//				.getAttribute(Constant.SESSION_MEMBER));
//		ReUtils.set(handOver, "createDate", DateTimeUtils.formatDate(
//				new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
//		return handOver;
//	}
//
//	@Override
//	// 2
//	public void post(HttpServletRequest request, HttpServletResponse response,
//			Object handler, ModelAndView modelAndView) {
//		// TODO Auto-generated method stub
//		/*
//		 * if(StringUtils.equalsIgnoreCase(request.getMethod(), "get")){
//		 * 
//		 * }
//		 */
//
//	}
//
//	private Object createImpth(HttpServletRequest request, Object bean, Impth i)
//			throws IllegalAccessException, InvocationTargetException,
//			NoSuchMethodException {
//		Object impth = new Impth();
//		ReUtils.set(impth, "compLog", bean);
//		// ReUtils.set(impth, "org", ReUtils.get(bean, "org"));
//		ReUtils.set(impth, "content", i.getContent());
//		ReUtils.set(impth, "enable", i.getEnable());
//		ReUtils.set(impth, "remark", i.getRemark());
//		ReUtils.set(impth, "parent", i);
//		if (StringUtils.isNotEmpty(i.getFirstDate())) {
//			ReUtils.set(impth, "firstDate", i.getFirstDate());
//		} else {
//			ReUtils.set(impth, "firstDate", i.getCreateDate());
//		}
//		// 待交接事项，计数+1；需处理事项，保持原值不变
//		if (StringUtils.equalsIgnoreCase(i.getEnable(), "2")) {
//			ReUtils.set(impth, "pasts", i.getPasts() + 1);
//		} else {
//			ReUtils.set(impth, "pasts", i.getPasts());
//		}
//
//		ReUtils.set(impth, "createDate", DateTimeUtils.formatDate(
//				new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
//		ReUtils.set(impth, "createMember",
//				request.getSession().getAttribute(Constant.SESSION_MEMBER));
//		return impth;
//	}
//
//	private Object createInjured(HttpServletRequest request, Object bean,
//			Injured i) throws IllegalAccessException,
//			InvocationTargetException, NoSuchMethodException {
//		Object injured = new Injured();
//		ReUtils.set(injured, "date", i.getDate());
//		ReUtils.set(injured, "time", i.getTime());
//		ReUtils.set(injured, "compLog", bean);
//		ReUtils.set(injured, "content", i.getContent());
//		ReUtils.set(injured, "enable", i.getEnable());
//		ReUtils.set(injured, "parent", i);
//		if (StringUtils.isNotEmpty(i.getFirstDate())) {
//			ReUtils.set(injured, "firstDate", i.getFirstDate());
//		} else {
//			ReUtils.set(injured, "firstDate", i.getCreateDate());
//		}
//		// 待交接，计数+1；需处理，保持原值不变
//		if (StringUtils.equalsIgnoreCase(i.getEnable(), "2")) {
//			ReUtils.set(injured, "pasts", i.getPasts() + 1);
//		} else {
//			ReUtils.set(injured, "pasts", i.getPasts());
//		}
//		ReUtils.set(injured, "createDate", DateTimeUtils.formatDate(
//				new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
//		ReUtils.set(injured, "createMember",
//				request.getSession().getAttribute(Constant.SESSION_MEMBER));
//		return injured;
//	}
//
//	private Object createComplain(HttpServletRequest request, Object bean,
//			Complain c) throws IllegalAccessException,
//			InvocationTargetException, NoSuchMethodException {
//		Object complain = new Complain();
//		ReUtils.set(complain, "date", c.getDate());
//		ReUtils.set(complain, "time", c.getTime());
//		ReUtils.set(complain, "compLog", bean);
//		// ReUtils.set(complain, "org", c.getOrg());
//		ReUtils.set(complain, "content", c.getContent());
//		ReUtils.set(complain, "enable", c.getEnable());
//		ReUtils.set(complain, "parent", c);
//		if (StringUtils.isNotEmpty(c.getFirstDate())) {
//			ReUtils.set(complain, "firstDate", c.getFirstDate());
//		} else {
//			ReUtils.set(complain, "firstDate", c.getCreateDate());
//		}
//		// 待交接，计数+1；需处理，保持原值不变
//		if (StringUtils.equalsIgnoreCase(c.getEnable(), "2")) {
//			ReUtils.set(complain, "pasts", c.getPasts() + 1);
//		} else {
//			ReUtils.set(complain, "pasts", c.getPasts());
//		}
//		ReUtils.set(complain, "createDate", DateTimeUtils.formatDate(
//				new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
//		ReUtils.set(complain, "createMember", request.getSession()
//				.getAttribute(Constant.SESSION_MEMBER));
//		return complain;
//	}
//
//	public Object findLastComp(Object bean) throws IllegalAccessException,
//			InvocationTargetException, NoSuchMethodException {
//
//		Object org = ReUtils.get(bean, "org");
//		DetachedCriteria dc = DetachedCriteria.forClass(Org.class);
//		dc.add(Restrictions.eq("id", ReUtils.getStr(org, "id")));
//		org = getService().findBean(dc);
//		
//		//车站类日志,根据B1或Y1班次,查找上一个班次
//		String shift = ReUtils.getStr(bean, "shift");
//		String date = ReUtils.getStr(bean, "date");
//		dc = DetachedCriteria.forClass(CompLog.class);
//		if (StringUtils.equalsIgnoreCase(shift, "Y1")) { // 已交班确认，enable=2
//			dc.add(Restrictions.eq("enable", "2"))
//					.add(Restrictions.eq("date", date))
//					.add(Restrictions.eq("org", org))
//					.add(Restrictions.eq("shift", "B1"));
//		} else {
//			Date today = DateTimeUtils.strToDate(date, "yyyy-MM-dd");
//			String yesterday = DateTimeUtils
//					.formatDate(new Date(today.getTime() - Constant.DAY_SPAN),
//							"yyyy-MM-dd");
//			dc.add(Restrictions.eq("enable", "2"))
//					.add(Restrictions.eq("date", yesterday))
//					.add(Restrictions.eq("org", org))
//					.add(Restrictions.eq("shift", "Y1"));
//		}
//		CompLog compLog = getService().findBean(dc);
//		return compLog;
//		
//		//2017-12-6部署为原策略，待单轨运行稳定两月后再部署此策略
//		//2017-9-7 更新---班次信息增多,改为根据创建时间判断
//	/*	dc = DetachedCriteria.forClass(CompLog.class);
//		dc.add(Restrictions.eq("org",org)).add(Restrictions.eq("enable","2"));
//		
//		dc.addOrder(Order.desc("createDate"));
//		List<CompLog> list = getService().find(dc);
//		if(list.size()>0){
//			return list.get(0);
//		}else{
//			return null;
//		}*/
//
//	}


	private Boolean needCreate(int pasts) {
		Boolean need = true;
		if ((pasts == 8) || (pasts == 109)) { // (pasts==9)||(pasts==110)
			need = false;
		}
		return need;
	}

	@Override
	public void after(HttpServletRequest request, HttpServletResponse response, Object handler) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void post(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {
		// TODO Auto-generated method stub
		
	}

}
